package com.example.file.win;

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class CharacterLimitFilter extends DocumentFilter {
    private int maxCharacters;

    public CharacterLimitFilter(int maxCharacters) {
        this.maxCharacters = maxCharacters;
    }

    @Override
    public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
        if (fb.getDocument().getLength() + string.length() <= maxCharacters) {
            super.insertString(fb, offset, string, attr);
        } else {
            // 如果插入后字符数超过限制，则只插入剩余字符
            int remaining = maxCharacters - fb.getDocument().getLength();
            if (remaining > 0) {
                super.insertString(fb, offset, string.substring(0, remaining), attr);
            }
        }
    }

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        if (fb.getDocument().getLength() + text.length() - length <= maxCharacters) {
            super.replace(fb, offset, length, text, attrs);
        } else {
            // 如果替换后字符数超过限制，则进行适当的替换
            int remaining = maxCharacters - (fb.getDocument().getLength() - length);
            if (remaining > 0) {
                super.replace(fb, offset, length, text.substring(0, remaining), attrs);
            }
        }
    }
}
